Page({
    data: {
        // 显示给用户看的公式
        formula: "",
        // 计算后的结果
        result: "",
        // 进行计算的公式
        formula_cacluete:"",
      },

    mixins: [require('../mixin/common')],

    // 清除本次的计算结果
    clear:function(e) {
        // console.log(e.currentTarget.dataset["info"])
        // console.log("hahahah")
        // console.log(e.currentTarget.dataset["ad"])
        // console.log(this.data.formula)
        this.setData({
            formula: "",
            result: "",
            formula_cacluete:""
        })
    },

    // 回退
    backspace:function(e){
        if(this.data.formula_cacluete.length == 0){
            return;
        }
        let mySet = new Set(["÷", "×", "-", "+"])
        if(mySet.has(this.data.formula_cacluete[this.data.formula_cacluete.length - 1])){
            this.setData({
                formula: this.data.formula.substring(0, this.data.formula.length - 3),
                formula_cacluete: this.data.formula_cacluete.substring(0, this.data.formula_cacluete.length - 1),
                result:""
            })
        }else{
            this.setData({
                formula: this.data.formula.substring(0, this.data.formula.length - 1),
                formula_cacluete: this.data.formula_cacluete.substring(0, this.data.formula_cacluete.length - 1),
                result:""
            })
        }
    },

    // 进行点击操作，添加字符
    add:function(e) {
        let mySet = new Set(["÷", "×", "-", "+"])
        var str = this.data.formula;
        var str_cacluete = this.data.formula_cacluete;
        if(str == ""){
            if(mySet.has(e.currentTarget.dataset["info"]) ||
            e.currentTarget.dataset["info"] == '=' ||
            e.currentTarget.dataset["info"] == '.'){
                return;
            }
            str = e.currentTarget.dataset["info"];
            str_cacluete = e.currentTarget.dataset["info"];
        } else {
            // 获取公示的最后一个字符
            let lastChar = str_cacluete.charAt(str.length - 1);
            if(mySet.has(lastChar) && mySet.has(e.currentTarget.dataset["info"])){
                return;
            }else{
                if(mySet.has(e.currentTarget.dataset["info"])){
                    str = str + " " + e.currentTarget.dataset["info"] + " ";
                }else{
                    str = str + e.currentTarget.dataset["info"];
                }
                str_cacluete = str_cacluete + e.currentTarget.dataset["info"];
            }
        }
        // console.log(str_cacluete)
        this.setData({
            formula: str,
            formula_cacluete: str_cacluete,
            result: ""
        })
    },

    // 点击 '=' 进行结果计算
    equal:function(e) {
        // 如果计算公式为空，那么点击计算式没用的
        if(this.data.formula_cacluete == ""){
            return;
        }
        let res;
        try{
            // 调用方法进行结果计算
            res = this.calculate(this.data.formula_cacluete)
        }catch(err){
            console.log(err)
            res = "error";
        }
        if(!isNaN(res)){
            // 将计算结果保存至缓存（最多保存一千条记录）
            let data = {}
            data['time'] = this.getData();
            data['res'] = this.data.formula_cacluete + "=" + res;
            // 操作缓存的结果了
            // 1. 获得缓存中的数据
            var historyData = wx.getStorageSync('historyData') || [] 
            // 2. 控制缓存中的数据
            if(historyData.length == 1000){
                historyData.shift()
            }
            historyData.push(data)
            // 保存至缓存中
            wx.setStorageSync('historyData', historyData)
        }
        // 更新界面的结果
        this.setData({
            // formula: str,
            result : "= " + res
        })
    },

    history:function(e){
        wx.navigateTo({
          url: '/pages/history/history',
        })
    },

    setting:function(e){
        wx.navigateTo({
          url: '/pages/setting/setting',
        })
    },

    // 获取年月日
    getData: function(){
        // 创建一个 Date 对象，表示当前时间
        let currentDate = new Date();

        // 获取当前的年、月、日
        let year = currentDate.getFullYear(); // 年
        let month = ('0' + (currentDate.getMonth() + 1)).slice(-2); // 月，月份从0开始，需要加1
        let day = ('0' + currentDate.getDate()).slice(-2); // 日

        // 格式化年月日
        let formattedDate = year + '年' + month + '月' + day + '日';
        return formattedDate;
    },

    // 对计算公式进行计算
    calculate: function (str){
        let stackNum = [];
        let stackOperate = [];
        for (let i = 0; i < str.length; i++) {
            // console.log(stackNum + "-------------" + stackOperate)
            let c = str.charAt(i);
            if (c == '(') {
                stackOperate.push(c);
            } else if (c == ')') {
                while (stackOperate[stackOperate.length - 1] != '(') {
                    this.operate(stackNum, stackOperate);
                }
                // 去掉"("操作符
                stackOperate.pop();
            } else if (c == '-' || c == '+' || c == '×' || c == '÷') {
                // 加减乘除符号
                while (stackOperate.length != 0 && this.getOperatePriority(c) <= this.getOperatePriority(stackOperate[stackOperate.length - 1])) {
                    this.operate(stackNum, stackOperate);
                }
                stackOperate.push(c);
            } else {
                // 数字
                let s = c;
                let j = i + 1
                for (; j < str.length; j++) {
                    let c1 = str.charAt(j);
                    if ((c1 >= '0' && c1 <= '9') || c1 == '.') {
                        s = s + c1;
                    } else {
                        break;
                    }
                }
                stackNum.push(parseFloat(s));
                // 查看如果最后一个是数字，那么直接跳出，不然继续循环。
                if(j == str.length){
                    break;
                }else{
                    i = j - 1;
                }
            }
        }
        // console.log(stackNum + "#############" + stackOperate)
        while (stackOperate.length != 0) {
            this.operate(stackNum, stackOperate);
        }
        console.log(stackNum + "-------------" + stackOperate)
        return stackNum.pop();
    },

    // 进行单次的结算过程
    operate: function(stackNum, stackOperate){
        let c = stackOperate.pop();
        let num2 = stackNum.pop();
        let num1 = stackNum.pop();
        switch (c) {
            case '-':
                stackNum.push(num1 - num2);
                break;
            case '+':
                stackNum.push(num1 + num2);
                break;
            case '×':
                stackNum.push(num1 * num2);
                break;
            case '÷':
                stackNum.push(num1 / num2);
                break;
        }
    },

    // 对符号进行优先级判别
    getOperatePriority:function(c){
        switch (c) {
            case '+':
            case '-':
                return 1;
            case '×':
            case '÷':
                return 2;
            default: // '('
                return 0;
        }
    },

    onLoad: function (option) {
    }

  });
  